import { watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute } from 'vue-router'

export function usePageTitle() {
  const { t, locale } = useI18n()
  const route = useRoute()

  // 根据路由名称获取对应的标题key
  const getTitleKey = (routeName: string | symbol | null | undefined): string => {
    switch (routeName) {
      case 'login':
        return 'title.login'
      case 'tasks':
        return 'title.tasks'
      case 'logs':
        return 'title.logs'
      case 'settings':
        return 'title.settings'
      default:
        return 'title.app'
    }
  }

  // 更新页面标题
  const updateTitle = () => {
    const titleKey = getTitleKey(route.name)
    document.title = t(titleKey)
  }

  // 更新HTML lang属性
  const updateLang = () => {
    document.documentElement.lang = locale.value
  }

  // 更新meta description
  const updateDescription = () => {
    const metaDescription = document.querySelector('meta[name="description"]')
    if (metaDescription) {
      metaDescription.setAttribute('content', t('meta.description'))
    }
  }

  // 监听语言变化
  watch(locale, () => {
    updateTitle()
    updateLang()
    updateDescription()
  }, { immediate: true })

  // 监听路由变化
  watch(() => route.name, () => {
    updateTitle()
  }, { immediate: true })

  return {
    updateTitle,
    updateLang,
    updateDescription
  }
} 